package cn.schoolwow.dns.interceptor;

import cn.schoolwow.quickserver.interceptor.HandlerInterceptor;
import cn.schoolwow.quickserver.interceptor.Interceptor;
import cn.schoolwow.quickserver.request.HttpRequest;
import cn.schoolwow.quickserver.response.HttpResponse;
import cn.schoolwow.quickserver.session.HttpSession;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

@Interceptor(patterns = "/**")
@Component
public class MDCInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpRequest httpRequest, HttpResponse httpResponse, HttpSession httpSession) throws IOException {
        MDC.put("requestId",UUID.randomUUID().toString());
        return true;
    }

    @Override
    public void postHandle(HttpRequest httpRequest, HttpResponse httpResponse, HttpSession httpSession) throws IOException {

    }

    @Override
    public void beforeResponse(HttpRequest httpRequest, HttpResponse httpResponse, HttpSession httpSession) throws IOException {
        httpResponse.setHeader("X-Request-Id",MDC.get("requestId"));
        MDC.remove("requestId");
    }
}
